from flask import Blueprint, jsonify, request, send_file
import pandas as pd
import numpy as np
from pathlib import Path
import os
import sys
import tempfile
import traceback
from holiday_business_travel_analysis import main as analyze_holiday_travel

# 创建蓝图
holiday_travel_bp = Blueprint('holiday_travel', __name__, url_prefix='/holiday-travel')

def get_resource_path(relative_path):
    """获取资源文件的绝对路径，支持开发环境和打包环境"""
    if hasattr(sys, '_MEIPASS'):
        # PyInstaller 打包环境
        base_path = sys._MEIPASS
    else:
        # 开发环境
        base_path = os.path.dirname(os.path.abspath(__file__))
    
    return os.path.join(base_path, relative_path)

# 数据文件路径
DATA_DIR = Path("data")
ALLDATA_DIR = DATA_DIR / "alldata"
RESULT_FILE = ALLDATA_DIR / "节假日出差分析结果.xlsx"

@holiday_travel_bp.route('/check-result-file', methods=['GET'])
def check_result_file():
    """检查分析结果文件是否存在"""
    try:
        exists = RESULT_FILE.exists()
        return jsonify({"success": True, "exists": exists})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)})

@holiday_travel_bp.route('/generate-analysis', methods=['POST'])
def generate_analysis():
    """生成分析数据"""
    try:
        success = analyze_holiday_travel()
        if success:
            return jsonify({"success": True})
        else:
            return jsonify({"success": False, "error": "分析过程出现错误"})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"success": False, "error": str(e)})

@holiday_travel_bp.route('/get-data', methods=['POST'])
def get_data():
    """获取分析结果数据"""
    try:
        if not RESULT_FILE.exists():
            return jsonify({"success": False, "error": "分析结果文件不存在"})

        # 读取Excel文件
        df = pd.read_excel(RESULT_FILE)
        
        # 处理 NaN 值和特殊数值
        df = df.replace({np.nan: None, np.inf: None, -np.inf: None})
        
        # 转换为字典列表，确保所有值都是 JSON 可序列化的
        data = df.to_dict('records')
        
        # 获取所有列名
        all_columns = df.columns.tolist()

        return jsonify({
            "success": True,
            "data": data,
            "all_columns": all_columns
        })
    except Exception as e:
        traceback.print_exc()
        return jsonify({"success": False, "error": str(e)})

@holiday_travel_bp.route('/download-excel')
def download_excel():
    """下载分析结果"""
    try:
        if not RESULT_FILE.exists():
            return jsonify({
                'error': '分析结果文件不存在'
            }), 404

        # 读取Excel文件
        df = pd.read_excel(RESULT_FILE)
        
        # 获取筛选条件
        show_level_one = request.args.get('level_one', 'true').lower() == 'true'
        show_level_two = request.args.get('level_two', 'true').lower() == 'true'
        show_level_three = request.args.get('level_three', 'true').lower() == 'true'
        selected_fields = request.args.getlist('fields')
        
        # 应用筛选条件
        if not (show_level_one and show_level_two and show_level_three):
            level_conditions = []
            if show_level_one:
                level_conditions.append(df['城市优先级'] == '一级')
            if show_level_two:
                level_conditions.append(df['城市优先级'] == '二级')
            if show_level_three:
                level_conditions.append(df['城市优先级'] == '三级')
                
            if level_conditions:
                df = df[pd.concat(level_conditions, axis=0)]

        # 如果指定了字段，只保留选择的字段
        if selected_fields:
            valid_fields = [field for field in selected_fields if field in df.columns]
            if not valid_fields:
                return jsonify({
                    'error': '没有找到有效的字段'
                }), 400
            df = df[valid_fields]

        # 如果数据为空，返回错误
        if df.empty:
            return jsonify({
                'error': '筛选后没有符合条件的数据'
            }), 400

        # 创建临时文件名
        filename_parts = ['节假日出差分析结果']
        if not (show_level_one and show_level_two and show_level_three):
            levels = []
            if show_level_one:
                levels.append('一级')
            if show_level_two:
                levels.append('二级')
            if show_level_three:
                levels.append('三级')
            if levels:
                filename_parts.append(f"{'_'.join(levels)}等级")
        filename = f"{'_'.join(filename_parts)}.xlsx"
        
        # 使用BytesIO直接在内存中处理Excel文件
        from io import BytesIO
        excel_buffer = BytesIO()
        
        # 直接写入内存流
        with pd.ExcelWriter(excel_buffer, engine='openpyxl') as writer:
            df.to_excel(writer, index=False)
        
        # 将指针移到开始位置
        excel_buffer.seek(0)
        
        return send_file(
            excel_buffer,
            as_attachment=True,
            download_name=filename,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )

    except Exception as e:
        print(f"下载文件时出错: {str(e)}")
        traceback.print_exc()
        return jsonify({
            'error': f'下载文件时出错: {str(e)}'
        }), 500 